# ===============================================
#  Filename: UDPListenServer.py
#     About: This file contains the UDP Listen
#            Server used by Hotel-Kilo to pick
#            up broadcasts from the client
# ===============================================
import sys
import socket
import traceback
from HkDisplay import HkDisplay

class UDPListenServer():
    
    networkInterface = ''
    oldAddress = ''
    port = 2600
    display = HkDisplay()
    
    def __init__(self, log=False):
        print '\n [*] Starting UDP listen server, press ctrl + break to exit...'
        if log:
            self.display.fileOuput = True
            print '\n [*] Saving data to log file (%s)' % self.display.fileOutputPath

    def createBroadcastSocket(self):
        ''' Creates a broadcast socket on self.port (defaults to 2600) '''
        self.networkInterface = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.networkInterface.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.networkInterface.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        self.networkInterface.bind(('', self.port))
        
    def start(self):
        ''' Create a listen server using "networkInterface" '''
        print '\n [*] Waiting for UDP hookers on port: %s' % self.port
        while True:
            try:
                message, address = self.networkInterface.recvfrom(8192)
                if str(address) != self.oldAddress:
                    self.display.newClient(address)
                    self.oldAddress = str(address)
                self.display.printMessage(message)
            except KeyboardInterrupt:
                print '\n [*] User exit requested, the listen server has been stopped.'
                sys.exit()
            except:
                traceback.print_exc()
                continue